package com.sky.course.controller;

import com.sky.course.entity.Course;
import com.sky.course.service.CourseClientService;
import com.sky.course.util.ExcelData;
import com.sky.course.util.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @Description:    文件下载及数据导出Excel
* @Author:         Joe
* @CreateDate:     2019/10/31 18:52
*/
@RestController
@RequestMapping(value = "/excel")
@Api(value = "Excel文件导出",description = "Excel文件导出")
public class ExcelController {

    @Autowired
    private CourseClientService courseClientService;

    @ApiOperation(value = "课程文件导出",notes = "课程Excel文件导出",produces = "application/octet-stream")
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public void excel(HttpServletResponse response) throws Exception {
        List<Course> list = courseClientService.list();
        ExcelData data = new ExcelData();
        data.setName("课程列表");
        //添加表头
        List<String> titles = new ArrayList<>();
        titles.add("ID");
        titles.add("名称");
        titles.add("数据库");
        data.setTitles(titles);
        
        //添加列
        List<List<Object>> rows = new ArrayList<>();
        List<Object> row = null;
        for (int i = 0; i < list.size(); i++) {
            row = new ArrayList<>();
            row.add(list.get(i).getCId());
            row.add(list.get(i).getCName());
            row.add(list.get(i).getDbSource());
            rows.add(row);
            
        }

        data.setRows(rows);

        SimpleDateFormat fdate=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String fileName=fdate.format(new Date())+".xls";
        ExcelUtils.exportExcel(response, fileName, data);
    }
}
